﻿using UnityEngine;

public class PlayerController : MonoBehaviour {

	public Vector2 speed = new Vector2 (50, 50);

	private Vector2 movement;

	void Update(){
		float inputX = Input.GetAxis ("Horizontal");
		float inputY = Input.GetAxis ("Vertical");

		movement = new Vector2 (
			speed.x * inputX,
			speed.y * inputY);

		bool shoot = Input.GetButtonDown ("Fire1");
		shoot |= Input.GetButtonDown ("Fire2");

		if (shoot) {
			WeaponScript weapon = GetComponent<WeaponScript>();
			if( weapon != null)
				weapon.Attack(false);
		}
	
	}

	void FixedUpdate() {

		
		// X axis
		if (transform.position.x <= -12.5f) {
			transform.position = new Vector2(-12.5f, transform.position.y);
		} else if (transform.position.x >= 12.5f) {
			transform.position = new Vector2(12.5f, transform.position.y);
		}
		
		// Y axis
		if (transform.position.y <= -10.5f) {
			transform.position = new Vector2(transform.position.x, -10.5f);
		} else if (transform.position.y >= 10.5f) {
			transform.position = new Vector2(transform.position.x, 10.5f);
		}

		rigidbody2D.velocity = movement;
	}

	void OnCollisionEnter2D(Collision2D collision)
	{
		bool damagePlayer = false;

		EnemyScript enemy = collision.gameObject.GetComponent<EnemyScript> ();

		if (enemy != null) {
			HealthScript enemyHealth = enemy.GetComponent<HealthScript> ();

			if(enemyHealth != null){
				enemyHealth.Damage(enemyHealth.hp);
				damagePlayer = true;
			}


		}
		if( damagePlayer)
		{
			HealthScript playerHealth = this.GetComponent<HealthScript>();
			if (playerHealth != null)
				playerHealth.Damage (1);
		}
	}
	
}
